import React, { Component,useContext, useState, useEffect, useRef } from 'react';
import adds from './adds.module.css'
import { Select, Button, Table, Input, Space , Popconfirm, Form} from 'antd';
const { Option } = Select;
const EditableContext = React.createContext();

const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

const EditableCell = ({
        title,
        editable,
        children,
        dataIndex,
        record,
        handleSave,
        ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef();
  const form = useContext(EditableContext);
  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };

  const save = async e => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      handleSave({ ...record, ...values });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };

  let childNode = children;

  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `${title} is required.`,
          },
        ]}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{
          paddingRight: 24,
        }}
        onClick={toggleEdit}
      >
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};
class AddStudent extends Component {
    state = {
        columns : [
            {
              title: '  座',
              dataIndex: 'key1',
              key:'key1',
              render: (value,item) =>value===true?<span style={{color:'red'}} onClick={()=>this.$message.warning('座位已有人')}>有人</span>:value==='green'?<span  style={{color:'green'}}>已选</span>:<span  style={{color:'#1990FF'}} onClick={()=>this.SETcolor(value,item)}>可选</span>
              
            },
            { 
              title: '位',
              dataIndex: 'key2',
              key:'key2'+'1',
              render: (value,item) =>value===true?<span style={{color:'red'}}  onClick={()=>this.$message.warning('座位已有人')}>有人</span>:value==='green'?<span  style={{color:'green'}}>已选</span>:<span  style={{color:'#1990FF'}} onClick={()=>this.SETcolor(value,item)}>可选</span>
            },
            {
              title: '表',
              dataIndex: 'key3',
              key:'key3'+'2',
              render: (value,item) =>value===true?<span style={{color:'red'}}  onClick={()=>this.$message.warning('座位已有人')}>有人</span>:value==='green'?<span  style={{color:'green'}}>已选</span>:<span  style={{color:'#1990FF'}} onClick={()=>this.SETcolor(value,item)}>可选</span>
            },
            {
              title: '选',
              dataIndex: 'key4',
              key:'key4'+'3',
              render: (value,item) =>value===true?<span style={{color:'red'}}  onClick={()=>this.$message.warning('座位已有人')}>有人</span>:value==='green'?<span  style={{color:'green'}}>已选</span>:<span  style={{color:'#1990FF'}} onClick={()=>this.SETcolor(value,item)}>可选</span>
            },
            {
              title: '择',
              dataIndex: 'key5',
              key:'key5'+'4',
              render: (value,item) =>value===true?<span style={{color:'red'}}  onClick={()=>this.$message.warning('座位已有人')}>有人</span>:value==='green'?<span  style={{color:'green'}}>已选</span>:<span  style={{color:'#1990FF'}} onClick={()=>this.SETcolor(value,item)}>可选</span>
            }
            ] ,
            dataSource: [
            ],
            count: 2,
            classdata:'',
            classnum:'',
        educationdata: '',
        classdata: '',
        studentName:'',
        studentage:'16',
        sex: '女',
        education: '研究生',
        className: '网站工程-1908A',
        setid:'',
        setArr:[],
        setid2:'',
        agelist:[16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40]
    }
    //颜色
    SETcolor=(value,item)=>{
      const {setid}=this.state
      if(setid===''){
         this.setState({setid:value+item.row*5,setid2:value+item.row*5})
         let data=[...this.state.dataSource]
         data.forEach(j=>{
            if(j.row===item.row){
                 let key='key'+(value)
                 j[key]='green'
            }
         })
         this.setState({dataSource:data})
         return 
      }else{
        this.setState({setid:value+item.row*5})
        let data=[...this.state.dataSource]
        data.forEach(j=>{
           if(j.row===item.row){
                let key='key'+(value)
                j[key]='green'
           }
           let row=Math.ceil(this.state.setid2/5)-1
           let key=this.state.setid2-(Math.ceil(this.state.setid2/5)-1)*5
           let itemkey='key'+key
           console.log(j.row,row,j[itemkey],key)
          if(j.row==row&&j[itemkey]=='green'){
              j[itemkey]=key
          }
        })
        this.setState({setid2:value+item.row*5})
      }
    }
    // //改变座位id
    // changeSET=(value,item)=>{
    //   console.log(item)
    //     const {setid}=this.state
    //      if(setid===''){
    //         this.setState({setid:value+item.row*5})
    //         let data=[...this.state.dataSource]
    //         data.forEach(j=>{
    //            if(j.row===item.row){
    //                 let key='key'+(value)
    //                 j[key]=true
    //            }
    //         })
    //         this.setState({dataSource:data})
    //         return 
    //      }
         
    //      this.$message.warning('您已选择座位')
    // }
    //座位表
    handleDelete = key => {
        const dataSource = [...this.state.dataSource];
        this.setState({
        dataSource: dataSource.filter(item => item.key !== key),
        });
    };

    handleSave = row => {
        const newData = [...this.state.dataSource];
        const index = newData.findIndex(item => row.key === item.key);
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        this.setState({
        dataSource: newData,
        });
    };
    //性别
    handleChange1 = value => {
        this.setState({ sex: value })
    }
    //学历
    handleChange2 = value => {
        this.setState({ education: value })
    }
    //班级
    handleChange3=value=>{
        this.setState({className:value})
        this.getlist(this.state.classdata,value)
        this.setlist(this.state.classdata,value)
    } 
    //年龄
    handleChange4=value=>{
        this.setState({studentage:value})
    } 
    //获取表格
    getlist=(data,clme)=>{
        let className=clme.split('-')
        data.forEach(item=>{
            if(item.school==className[0]&&item.className==className[1]){
                 this.setState({classnum:item.classType})
                 let count=item.classType
                 let newdata=[];
                 let i=0
                 while(count>0){
                     let obj= {
                       row:i,
                       key1: 1,
                       key2: 2,
                       key3: 3,
                       key4: 4,
                       key5: 5,
                     }
                     ++i
                     count=count-5
                     newdata.push(obj)
                 }
                 this.setState({dataSource:newdata})
                 return
            }
          })
    }
     //获取座位数据
     setlist=(data,clme)=>{
      let className=clme.split('-')
      data.forEach(item=>{
          if(item.className==className[1]&&item.school==className[0]){
                this.$httpReq(this.$api.getSetList({classid:item.classid}), res => {
                    const {code,data}=res;
                    if( data[0]&&data[0].studentList&&code){
                        this.setState({setArr:[...data[0].studentList.split(',')]})
                         data[0].studentList&&data[0].studentList.split(',').forEach(j=>{
                            let newdata=[...this.state.dataSource];
                            let row=Math.ceil(j/5)-1
                            let key=j-(Math.ceil(j/5)-1)*5
                            let itemkey='key'+key
                            newdata.forEach(item=>{
                               if(item.row==row&&item[itemkey]==key){
                                  item[itemkey]=true
                               }
                            })
                             this.setState({dataSource:newdata})
                         })
                    }
                })
                return
          }
        })
  }
     
    //添加学生
    addstu=()=>{
        const {sex,education,className,studentName,studentage,setid}=this.state;
        if(education===''||className===''||studentName===''||studentage===''||sex===''){
              this.$message.warning('请输入完整信息')
              return
        }
       if(setid===''){
            this.$message.warning('请选择座位')
            return
       }
        this.state.classdata.forEach(item=>{
            if(item.className==className.split('-')[1]&&item.school==className.split('-')[0]){
                this.$httpReq(this.$api.addStudent({name:studentName,age:studentage,sex,education,classid:item.classid,setid}),res=>{
                      const {code,msg}=res;
                      if(code){
                  
                        this.props.history.push('/home/student/setStudent')

                         this.$message.success(msg)
                      }
                })
                return
            }
        })
       
    }
  render(){
    const { educationdata,classdata,sex,education,className,dataSource,columns,studentName,studentage,agelist } = this.state;
        const components = {
        body: {
            row: EditableRow,
            cell: EditableCell,
        },
        };
     return <div className={adds.box}>
           <div className={adds.div}>学生姓名:<Input placeholder="请输入学生姓名" style={{ width: 320 }} className={adds.dinginp} value={studentName} onChange={e=>this.setState({studentName:e.target.value})}/></div>
           <div className={adds.div}>年龄:<Select value={studentage} style={{ width: 320 }} onChange={this.handleChange4} className={adds.dinginp}>
                                             {
                                               agelist&&agelist.map(item=>{
                                                  return  <Option value={item} key={item}>{item}</Option>
                                               })
                                             }
                                          </Select>
          </div>
           <div className={adds.div}>性别:<Select value={sex} style={{ width: 320 }} onChange={this.handleChange1} className={adds.dinginp}>
                              <Option value="女">女</Option>
                              <Option value="男">男</Option>
                          </Select>
           </div>
           <div className={adds.div}>学历:<Select value={education} style={{ width: 320 }} onChange={this.handleChange2} className={adds.dinginp}>
                             {
                               educationdata&&educationdata.map(item=>{
                                  return  <Option value={item} key={item}>{item}</Option>
                               })
                             }
                          </Select>
           </div>
           <div className={adds.div}>所属班级:<Select value={className} style={{ width: 320 }} onChange={this.handleChange3} className={adds.dinginp}>
                             {
                               classdata&&classdata.map(item=>{
                                   return <Option value={item.school+'-'+item.className} key={item.classid}>{item.school+'-'+item.className}</Option>
                               })
                             }
                          </Select>
          </div>
          <Button type="primary" style={{width:'100px',margin:'25px'}}onClick={()=>this.addstu()}>添加学生</Button>
          <Table  
                components={components}
                rowClassName={() => 'editable-row'}
                bordered
                dataSource={dataSource}
                columns={columns}
                style={{width:'50%',position:'absolute',right:'2%',top:'3%',textAlign:'center'}}
                pagination={false}
                rowKey={item=>item.row} 
            />
     </div>
   
  }
  componentDidMount(){
        //获取班级数据
        this.$httpReq(this.$api.getStudentList(),res=>{
            const {code,data}=res;
            if(code){
                this.setState({classdata:data.classData})
                this.getlist(data.classData,this.state.className)
                this.setlist(data.classData,this.state.className)
            }
        })
        //获取学历数据
        this.$httpReq(this.$api.getEducationList(), res => {
            const { code, data } = res;
            if (code) {
                this.setState({ educationdata: data })
            }
        })
    }
}
export default AddStudent
